/*
 * @Date: 2023-06-27 17:31:47
 * @作者: 七星玉蘅
 * @邮箱: 1532250426@qq.com
 * @LastEditTime: 2023-06-28 09:19:26
 * @FilePath: \kaifamiao\client\src\utils\router.js
 */
const sqlFn = require('./mysql')
const url = require('url')
const querystring = require('querystring')
const fs = require('fs')
const { log } = require('console')
//导出函数
module.exports = (req, res) => {
    //解析请求路径
    const { pathname, query } = url.parse(req.url, true)
    console.log(pathname)
    console.log(req.method)
    //判断请求方式
    if (req.method == 'POST') {

        //接受参数
        let params = ''
        req.on('data', (chunk) => {
            params += chunk
        })
        req.on('end', () => {
            console.log(params)
            //转换字符串为键值对
            let body = querystring.parse(params)

            if (req.headers['content-type'] == 'application/json') {
                body = JSON.parse(params)
            }
            // 处理新增数据的请求
            if (pathname == '/api/add') {
                // console.log("/add");
                console.log("获取的数据:", body)
                sqlFn('insert into `rank`(username,end_time,time, numbers, difficulty_factor, points) values (?,?,?, ?, ?, ?) ', [body.username, body.end_time, body.time, body.numbers, body.difficulty_factor, body.totalScore], (results) => {
                    console.log(results.affectedRows)
                    //告诉客户端成功了
                    if (results.affectedRows) {
                        res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
                        res.end(JSON.stringify({ code: 0, message: '操作成功' }))
                    }
                })
            }
        })

    }
    if (req.method == 'GET') {
        // 处理获取数据请求
        if (pathname == '/api/getlist') {
            // where ${query.name ? 'name=?' : 'name is not null'}`, [query.name]
            sqlFn('select * from `rank` order by points desc', null, (results) => {
                // console.log(results)
                res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
                res.write(JSON.stringify({ code: 0, records: results }))
                res.end()
            })
        }
        //处理获取html页面请求
        // if (pathname == '/index.html') {
        //     fs.readFile('./index.html', (err, data) => {
        //         if (err) {
        //             throw err
        //         }
        //         res.writeHead(200, { "Content-Type": 'text/html;charset=utf8' })
        //         res.write(data)
        //         res.end()
        //     })
        // }
    }
}